<template>
  <div class="my-applications">
    <div class="container">
      <h1 class="page-title">我的申请</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="applications.length === 0" class="empty-container">
        <el-empty description="您还没有提交过领养申请">
          <router-link to="/pets">
            <el-button type="primary">去看看宠物</el-button>
          </router-link>
        </el-empty>
      </div>
      
      <template v-else>
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="全部申请" name="all">
            <application-list :applications="applications" />
          </el-tab-pane>
          <el-tab-pane label="待审核" name="pending">
            <application-list :applications="pendingApplications" />
          </el-tab-pane>
          <el-tab-pane label="已通过" name="approved">
            <application-list :applications="approvedApplications" />
          </el-tab-pane>
          <el-tab-pane label="已拒绝" name="rejected">
            <application-list :applications="rejectedApplications" />
          </el-tab-pane>
          <el-tab-pane label="已取消" name="cancelled">
            <application-list :applications="cancelledApplications" />
          </el-tab-pane>
        </el-tabs>
      </template>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import ApplicationList from '@/components/adoptions/ApplicationList.vue';
import axios from 'axios';

export default {
  name: 'MyApplications',
  components: {
    ApplicationList
  },
  data() {
    return {
      activeTab: 'all',
      loading: true,
      loadError: null,
      applications: []
    };
  },
  computed: {
    ...mapGetters({
      loading: 'isLoading'
    }),
    pendingApplications() {
      return this.applications.filter(app => app.status === 'pending');
    },
    approvedApplications() {
      return this.applications.filter(app => app.status === 'approved');
    },
    rejectedApplications() {
      return this.applications.filter(app => app.status === 'rejected');
    },
    cancelledApplications() {
      return this.applications.filter(app => app.status === 'cancelled');
    }
  },
  async created() {
    // 从URL获取活动标签
    const { tab } = this.$route.query;
    if (tab && ['all', 'pending', 'approved', 'rejected', 'cancelled'].includes(tab)) {
      this.activeTab = tab;
    }
    
    await this.fetchApplications();
  },
  methods: {
    ...mapActions({
      fetchMyApplications: 'adoptions/fetchMyApplications'
    }),
    handleTabClick() {
      // 更新URL查询参数
      this.$router.push({ 
        query: { 
          ...this.$route.query, 
          tab: this.activeTab 
        } 
      }).catch(() => {});
    },
    async fetchApplications() {
      this.loading = true;
      this.loadError = null;
      
      try {
        // 获取认证令牌
        const token = sessionStorage.getItem('token') || this.$store.getters['auth/token'] || '';
        
        if (!token) {
          this.$message.error('登录状态已失效，请重新登录');
          this.$router.push('/login?redirect=/my-applications');
          return;
        }
        
        console.log('发送请求获取我的申请');
        
        const response = await axios.get('/api/adoptions/my-applications', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token
          }
        });
        
        console.log('获取申请列表响应:', response.data);
        
        if (Array.isArray(response.data)) {
          this.applications = response.data;
        } else if (response.data && Array.isArray(response.data.applications)) {
          this.applications = response.data.applications;
        } else {
          console.warn('接收到的申请数据格式不符合预期:', response.data);
          this.applications = [];
        }
      } catch (error) {
        console.error('获取申请列表失败:', error);
        this.loadError = error.message || '无法加载您的申请数据';
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.my-applications {
  padding: 40px 0;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}
</style> 